package com.baizhi.action;

import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import com.baizhi.entity.Cart;
import com.baizhi.entity.Order;
import com.baizhi.entity.OrderItem;
import com.baizhi.entity.User;
import com.baizhi.service.OrderItemService;
import com.baizhi.service.OrderService;
import com.baizhi.service.impl.OrderItemServiceImpl;
import com.baizhi.service.impl.OrderServiceImpl;
import com.opensymphony.xwork2.ActionSupport;

/**
 * @author 王雪洋
 * @Time 2017年5月4日 下午3:02:16
 * @disc:订单项处理的action
 */
public class OrderAction extends ActionSupport{
	private Order order = new Order();
	private Double totalprice;
	private OrderService os = new OrderServiceImpl();
	private OrderItem oi = null;
	private OrderItemService ois = new OrderItemServiceImpl();
	private HttpSession session = ServletActionContext.getRequest().getSession();
	private Integer addressid;
	/*
	 * 检测用户是否已登录
	 */
	public String checkUserLogin(){
		User u = (User) session.getAttribute("user");
		if(u != null){
			return SUCCESS;
		}else{
			//记录登录状态值
			session.setAttribute("userflag", "F");
			return "nologin";
		}
	}
	/*
	 * 添加新的订单
	 */
	public String addOrderItem(){
		//创建一个订单对象
		Order o = new Order();
		//填充订单信息
		//生成订单编号
		String s = (new Date()).getTime()+"";
		o.setOrdernum(s);
		//订单总价
		CartAction ca = new CartAction();
		o.setTotalprice(ca.getTotalprice());
		//订单创建时间
		o.setCreatetime(new Date());
		//订单状态未完成
		o.setOrderstatus("N");
		//地址ID
		/*Integer addressid = (Integer) session.getAttribute("addressid");*/
		o.setAddressid(addressid);
		//拿到当前用户ID
		User u = (User) session.getAttribute("user");
		o.setUserid(u.getUserid());
		//存值栈
		order = o;
		//插入数据库
		int a = os.insertOrder(o);
		//订单项表
		oi = new OrderItem();
		Map map = (Map) ServletActionContext.getRequest().getSession().getAttribute("cmap");
		//从map中取出商品逐个添加购物项到数据库
		if(map != null && a !=0 ){
			for (Object m : map.keySet()) {
				Cart c = (Cart) map.get(m);
				if(c.getPflag()==1){
					oi.setOrderitemcount(c.getPnum());
					oi.setOrderid(a);
					oi.setProductid(c.getProduct().getP_id());
					int ii = ois.insertOrderItem(oi);
					if(ii>0){
						//添加成功！
						map.remove(m);
					}
				}
			}
		}
		return SUCCESS;
	}
	/*
	 * 控制订单项
	 */
	public String changeItem(){
		
		return SUCCESS;
	}
	public Order getOrder() {
		return order;
	}
	public void setOrder(Order order) {
		this.order = order;
	}
	public Double getTotalprice() {
		return totalprice;
	}
	public void setTotalprice(Double totalprice) {
		this.totalprice = totalprice;
	}
	public Integer getAddressid() {
		return addressid;
	}
	public void setAddressid(Integer addressid) {
		this.addressid = addressid;
	}
}
